package com.song.seckill.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 创建 Jedis 的 util
 */

public class RedisUtil {

    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    private static JedisPool jedisPool;

    static {
        // 初始化连接池配置
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(100); // 最大连接数
        poolConfig.setMaxIdle(50);   // 最大空闲连接
        poolConfig.setMinIdle(10);   // 最小空闲连接
        poolConfig.setTestOnBorrow(true); // 借出连接时测试可用性

        // 建议从配置文件读取 host 和 port
        String host = "127.0.0.1";
        int port = 6379;
        jedisPool = new JedisPool(poolConfig, host, port);
    }

    /**
     * 获取 Jedis 实例
     */
    public static Jedis getJedis() {
        try {
            return jedisPool.getResource();
        } catch (Exception e) {
            logger.error("获取 Jedis 资源失败", e);
            return null;
        }
    }

    /**
     * 设置键值对
     */
    public static void set(String key, String value) {
        try (Jedis jedis = getJedis()) {
            if (jedis == null) return;
            jedis.set(key, value);
        } catch (Exception e) {
            logger.error("Redis set 操作失败，key: {}", key, e);
        }
    }

    /**
     * 获取键对应的值
     */
    public static String get(String key) {
        try (Jedis jedis = getJedis()) {
            if (jedis == null) return null;
            return jedis.get(key);
        } catch (Exception e) {
            logger.error("Redis get 操作失败，key: {}", key, e);
            return null;
        }
    }

    /**
     * 删除指定键
     */
    public static void delete(String key) {
        try (Jedis jedis = getJedis()) {
            if (jedis == null) return;
            jedis.del(key);
        } catch (Exception e) {
            logger.error("Redis delete 操作失败，key: {}", key, e);
        }
    }

    /**
     * 设置带过期时间的键值对
     */
    public static void setex(String key, int expireTime, String value) {
        try (Jedis jedis = getJedis()) {
            if (jedis == null) return;
            jedis.setex(key, expireTime, value);
        } catch (Exception e) {
            logger.error("Redis setex 操作失败，key: {}", key, e);
        }
    }
}

